<?php
declare(strict_types=1);

namespace App\Service\Pushapp;
use Exception;
use Hyperf\Guzzle\ClientFactory;
use Psr\Log\LoggerInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use JPush\Client as Jclient;
/**
 * 极光推送
 */
class JpushService
{
	protected ClientFactory $clientFactory;

    protected LoggerInterface $logger;

    protected $redis;

    private  $jclient;

    private bool $apns_production;

    public function __construct(ClientFactory $clientFactory,LoggerFactory $loggerFactory)
    {
        $this->clientFactory = $clientFactory;
        $this->logger = $loggerFactory->get('log', 'default');
        $container = ApplicationContext::getContainer();
        $this->redis = $container->get(\Hyperf\Redis\Redis::class);
        $cfg = config('pushappconfig.jpush', []);
        $this->jclient = new Jclient($cfg['app_key'], $cfg['master_secret'],null);
        $this->apns_production = env('APP_ENV', "")=='prod'?true:false;
        // $this->apns_production = false;
    }
    /**
     * 单推
     * @param array $push_data
     * @param string $reg_id
     * @return array
     */
    public function sPush(array $push_data,string $reg_id)
    {
        $push = $this->jclient->push();
        $push->setPlatform($push_data['platform'])
            ->addRegistrationId($reg_id);
        switch ($push_data['platform']) {
            case 'ios':
                $push->iosNotification([
                    'title' => $push_data['title'], //可选设置
                    'body' => $push_data['content']//必填，否则通知栏不展示
                ],[
                    //'subtitle' => $push_data['subtitle'],
                    'sound' => 'sound',
                    'badge' => '+1',
                    'content-available' => true,
                    'extras' => $push_data['extra'],
                ]);
                break;
            case 'android':
                $push->androidNotification($push_data['content'],[
                    'title' => $push_data['title'],
                    'builder_id' => 0,
                    'extras' => $push_data['extra'],
                ]);
                break;
            default:
                return ['status'=>0,'msg'=>'缺少必要尝试platform'];
        }
        $response = $push->options(['apns_production' => $this->apns_production])->send();
        return ['status'=>1,'data'=>$response];
    }
}